﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MultiTenantDemo.Context;
using MultiTenantDemo.Entity;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using Dapper.Contrib.Extensions;

namespace MultiTenantDemo.Controllers
{
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherForecastController : ControllerBase
    {
        private static readonly string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly DbContext _testDbContext;

        public WeatherForecastController(ILogger<WeatherForecastController> logger,TestDbContext testDbContext)
        {
            _logger = logger;
            _testDbContext = testDbContext;
        }

        [HttpGet]
        public async Task<IEnumerable<User>> Get()
        {
            //var list = await _testDbContext.Set<User>().ToListAsync();
            var conn = _testDbContext.Database.GetDbConnection();
            //ait conn.OpenAsync();
            var list = await conn.GetAllAsync<User>();
            return list;
        }

        [HttpPost]
        public async Task<User> AddUser(User user)
        {
            var list = new List<User>();
            //for (int i = 0; i < 900000; i++)
            //{
            //    list.Add(new User { Name = $"测试姓名{i + 1}", Age = 20, Birthday = DateTimeOffset.Now, RoleId = 1, Sex = i % 2 == 0 ? Enum.SexEnum.Male : Enum.SexEnum.Female });
            //}

            using (var tran = await _testDbContext.Database.BeginTransactionAsync())
            {
                
                var conn = tran.GetDbTransaction().Connection;
                await conn.InsertAsync(new Role { Name = "随机角色" }, tran.GetDbTransaction());
                await conn.InsertAsync(new User { Name = "1111", Age = 10, Birthday = DateTimeOffset.Now, RoleId = 1, Sex = Enum.SexEnum.Female },tran.GetDbTransaction());
                //await _testDbContext.Set<User>().AddAsync(user);
                //await _testDbContext.SaveChangesAsync();
                //await _testDbContext.Set<Role>().AddAsync(new Role { Name = "测试角色" });
                //await _testDbContext.SaveChangesAsync();
                //await _testDbContext.BulkInsertAsync(list, tran.GetDbTransaction() as MySqlConnector.MySqlTransaction);
                //await _testDbContext.SaveChangesAsync();
                await tran.CommitAsync();
            }

            return user;
        }
    }
}
